//
//  NetworkConfig.m
//  ServiceCode
//
//  Created by 曹连华 on 2020/3/27.
//

#import "NetworkConfig.h"
#import <CoreCode/CoreCode.h>

@implementation NetworkDomainModel

+ (NetworkDomainModel *)modelTitle:(NSString *)title
                     networkDomain:(NSString *)networkDomain
                     securedDomain:(NSString *)securedDomain {
    return [NetworkDomainModel modelTitle:title networkDomain:networkDomain securedDomain:securedDomain netWorkH5Domain:@"" securedH5Domain:@""];
}

+ (NetworkDomainModel *)modelTitle:(NSString *)title
                     networkDomain:(NSString *)networkDomain
                     securedDomain:(NSString *)securedDomain
                   netWorkH5Domain:(NSString *)netWorkH5Domain
                   securedH5Domain:(NSString *)securedH5Domain {
    NetworkDomainModel *model = [NetworkDomainModel new];
    model.networkTitle = title;
    model.networkDomain = networkDomain;
    model.securedDomain = securedDomain;
    model.netWorkH5Domain = netWorkH5Domain;
    model.securedH5Domain = securedH5Domain;
    return model;
}
@end

NSString *const NetworkForceHttpKey = @"NetworkForceHttpKey";

@interface NetworkConfig ()

@property (nonatomic, strong) NSMutableArray<NetworkDomainModel *>*domains;

@property (nonatomic, strong) NetworkDomainModel *onlineNetworkDomain;
@property (nonatomic, strong) NetworkDomainModel *currentNetworkDomain;

@end

@implementation NetworkConfig

@synthesize forceHttp;

DEF_SINGLETON(NetworkConfig)

+ (JSONKeyMapper *)keyMapper {
    return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{@"systemVersion": @"clientVersion",
                                                                  @"appVersion": @"clientAppVersion"
                                                                  }];
}

- (id)init {
    self = [super init];
    if (self) {
        _nettype = @"";
        _systemVersion = [[UIDevice currentDevice] systemVersion];
        _appVersion = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        _deviceCode = [NSString stringWithString:[[[UIDevice currentDevice] identifierForVendor] UUIDString]];
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            _clientSystem = @"iPhone";
            _traderName = @"iosSystem";
        } else {
            _clientSystem = @"iPad";
            _traderName = @"iPadSystem";
        }
    }
    
    return self;
}

- (NSMutableArray<NetworkDomainModel *> *)domains {
    if(!_domains) {
        _domains = [NSMutableArray<NetworkDomainModel *> array];
    }
    return _domains;
}

- (NetworkDomainModel *)currentNetworkDomain {
        BOOL debug = false;
    #if DEBUG
        debug = true;
    #endif
    if (!debug) {
        return self.onlineNetworkDomain;
    } else {
        return _currentNetworkDomain;
    }
}

- (void)setLongitude:(NSNumber *)longitude {
    _longitude = longitude;
}

- (void)setLatitude:(NSNumber *)latitude {
    _latitude = latitude;
}

- (void)setOnlineNetworkDomain:(NetworkDomainModel *)onlineNetworkDomain {
    _onlineNetworkDomain = onlineNetworkDomain;
    self.currentNetworkDomain = onlineNetworkDomain;
}

- (void)setNetworkDomains:(NSArray<NetworkDomainModel *>*)domains {
    if (domains.count <= 0) { return; }
    [self.domains removeAllObjects];
    [self.domains addObjectsFromArray:domains];
}

- (void)setForceHttp:(BOOL)forceHttp {
    if (NetworkForceHttpKey && [NetworkForceHttpKey isKindOfClass:[NSString class]]) {
        [[NSUserDefaults standardUserDefaults] setObject:@(forceHttp) forKey:NetworkForceHttpKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (BOOL)isForceHttp {
    NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:NetworkForceHttpKey];
    if ([number isKindOfClass:[NSNumber class]]) {
        return [number boolValue];
    } else {
        return NO;
    }
}

- (NSDate *)serverTime {
    //根据本地时间与服务器时间的差异 算出的当前服务器的时间  **不要乱改，其他地方有用到
    _serverTime = [NSDate dateWithTimeIntervalSinceNow:self.dTime];
    return _serverTime;
}

- (NSString *)serverTimestamp {
    return [NSString stringWithFormat:@"%0.0lf", [[NSDate date] timeIntervalSince1970] + self.dTime];
}
/**
 * 功能:获取签名字符串
 */
- (NSString *)getSignature:(NSDictionary *)aDict {
    NSMutableDictionary *theDict = [aDict mutableCopy];
    //signature_method
    [theDict setObject:@"md5" forKey:@"signature_method"];
    //timestamp
    [theDict setObject:self.serverTimestamp?:@"" forKey:@"timestamp"];
    //trader
    [theDict setObject:self.traderName?:@"" forKey:@"trader"];
    
    //拼装
    NSMutableString *mString = [NSMutableString string];
    NSArray *queryPairs = [CoreNetworkQuery queryPairsFromDictionary:theDict];
    NSArray *sortedQueryPairs = [queryPairs sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    for (PBQueryPair *queryPair in sortedQueryPairs) {
        if ([queryPair queryString]) {
            [mString appendString:[queryPair queryString]];
        }
        
    }
    
    //加上私钥
    NSString *signatureKey = self.signatureKey;
    [mString appendString:signatureKey?:@""];
    
    //md5运算
    NSString *signature = mString.md5String;
    signature = [signature uppercaseString];
    
    return signature;
}

/**
 *  功能:获取AES加密的token
 */
- (NSString *)getAesEncodedToken {
    NSString *token = self.token;
    if (token == nil) {
        return nil;
    }
    
    // 接口要求毫秒数
    long long time = [[self serverTimestamp]longLongValue];
    NSString *totalStr = [NSString stringWithFormat:@"%@::%lld", token, time * 1000];
    NSString *signatureKey = self.signatureKey;
    
    return signatureKey ? [totalStr encryptByAESKey:signatureKey] : nil;
}

/**
 * 切换网络h环境
 */
- (void)switchNetworkDomain {
    
    NSMutableArray *titles = [NSMutableArray array];
    for (NetworkDomainModel *model in self.domains) {
        NSString *title = model.networkTitle;//[NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@",model.networkTitle,model.networkDomain,model.securedDomain,model.netWorkH5Domain,model.securedH5Domain];
        [titles safeAddObject:title];
    }
    
    WEAK_SELF;
    [CoreAlertController alertSheetWithTitle:@"网络环境切换" message:nil actions:titles andCompleteBlock:^(NSInteger buttonIndex) {
        STRONG_SELF;
        if (buttonIndex >= 0) {
            self.currentNetworkDomain = [self.domains safeObjectAtIndex:buttonIndex];
            [[UIApplication sharedApplication].keyWindow.rootViewController.view showLoadingWithMessage:[NSString stringWithFormat:@"已成功切换到%@",self.currentNetworkDomain.networkTitle] hideAfter:2.3];
        }
    }];
}

@end
